module.exports = (EdtApi) => {
  "use strict";
  let chatId = "", count = 0;
  function isGroup() {
    return false;
  }
  async function getChatId(times = 0) {
    let url = window.location.href;
    const regex = /\/conversation\/(\d+)\/?/;
    const match = regex.exec(url);
    let id = null;
    try {
      if (match) id = match[1];
    } catch (error) {
      console.log('获取对话id失败', error)
    }
    if (id && id != chatId) return id;
    await EdtApi.sleep(50);
    if (times > 10) return id;
    times++;
    return getChatId(times);
  }
  return {
    config: {
      friendList: "ion-menu.split-pane-side",//无
      chat: 'section.split-pane-main',
      msgBox: 'communications-detail-page:not(.ion-page-hidden) ion-content.conversation-container',
      input: 'communications-detail-page:not(.ion-page-hidden) ion-footer chat-input form ion-textarea textarea.native-textarea',
      inMsg: '.messages-container .text-message .received-message',
      outMsg: '.messages-container .text-message .sent-message',
      allMsg: ".messages-container .text-message ion-label.text-item",
      sendBtn: 'communications-detail-page:not(.ion-page-hidden) button.send-message--button',
      setting: "communications-detail-page:not(.ion-page-hidden) chat-input form div.form-container",
      tips: {
        in: 'communications-detail-page:not(.ion-page-hidden) div.address-header address-bar div.address-left section.address-left__common',
        out: 'communications-detail-page:not(.ion-page-hidden) ion-footer.footer-md'
      },
      crm: {
        // listener: '#LeftColumn-main',
        top: 'communications-detail-page:not(.ion-page-hidden) div.address-header address-bar div.address-left section.address-left__common',
        left: ""
      },
      placeholder: {
        selector: "communications-detail-page:not(.ion-page-hidden) ion-footer chat-input form ion-textarea textarea.native-textarea",
        attr: "placeholder"
      },
      extra: {//其他会触发对话框变动的情况处理
        selector: "ion-menu.split-pane-side",
        level: 30,
        delay: 1000,
      },
      initChat: true,
      inputType: "input",
      sendType: "keyup",
      autoCount: 20
    },
    init(handler) {
      EdtApi.queryWait({
        selector: 'weblayout-page',
        interval: 200,
        timeout: 60000
      }).then(main => {
        main && EdtApi.sendToHost("webview-checked");
      }).catch(err => {
        console.error(err);
      });
      let isChecked = window.location.href.includes("checked=1");
      if (isChecked) setTimeout(() => {
        EdtApi.sendToHost("webview-checked");
      }, 1000);
      EdtApi.queryWait({
        selector: '#username input.native-input',
        interval: 500,
        timeout: 100000
      }).then(username => {
        let checkbox = document.querySelector('#keepLoggedInLabel ion-checkbox');
        let keepLoggedIn = checkbox?.shadowRoot.querySelector('label.checkbox-wrapper input[type="checkbox"]');
        if (!keepLoggedIn.checked) checkbox?.click();
        if (isChecked || !username) return;
        let password = document.querySelector('#password input.native-input');
        if (!password) return;
        username.value = '123456@qq.com';
        password.value = '123456';
        const evt = document.createEvent("HTMLEvents");
        evt.initEvent("input", true, true);
        username?.dispatchEvent(evt);
        password?.dispatchEvent(evt);
        !isChecked && this.testLogin();
      }).catch(err => {
        console.error(err);
      });
      EdtApi.queryWait({
        selector: this.config.chat,
        interval: 500,
        timeout: 1000000
      }).then(box => {
        // console.log(box);
        handler?.initChat.call(handler, null);
      }).catch(err => {
        console.error(err);
      });
      EdtApi.queryWait({
        selector: 'ion-list[role="list"]',
        interval: 500,
        timeout: 1000000
      }).then(box => {
        // console.log(box);
        let _id;
        let observer = new MutationObserver(async (mutations) => {
          console.log(mutations);
          _id = chatId;
          chatId = await getChatId();
          chatId = _id;
          handler?.initChat.call(handler, null);
        });
        observer?.observe(box, {
          attributes: true,
          subtree: true
        });
      }).catch(err => {
        console.error(err);
      });
    },
    testLogin() {
      let btn = document.querySelector('app-login sc-button>ion-button');
      btn?.click();
      setTimeout(() => {
        let url = window.location.href;
        window.location = url + "?checked=1";
      }, 6000);
    },
    getUnread() {
      return count;
    },
    getChatInfo() {
      return new Promise(async (resolve) => {
        chatId = await getChatId();
        resolve({ id: chatId, isGroup: isGroup() });
      });
    },
    getChatTitle(chatEl) {
      let titleEl = (chatEl || document).querySelector('communications-detail-page:not(.ion-page-hidden) div.address-header address-bar div.address-left section.address-left__common ion-label');
      return titleEl?.textContent || "";
    },
    getChatIds() {
      return [];
    },
    getText(msgBox) {
      return msgBox?.textContent || "";
    },
    getIptMsg(inputEl) {
      return inputEl?.value || "";
    },
    getUserInfo() {
      try {
        let userEl = document.querySelector('ion-item.number-item ion-label h3');
        let userName = userEl?.textContent || "";
        let avatar = "";
        let account = "";
        return {
          avatar,
          userName,
          account
        };
      } catch (error) {
        return null;
      }
    }
  }
};